<template>
  <div>
    <p>
      <button @click="list(1)" class="btn btn-white btn-default btn-round">
        <i class="ace-icon fa fa-refresh"></i>
        刷新
      </button>
      &nbsp;&nbsp;
      <button v-show="hasResources('010101')" @click="addModel()" class="btn btn-white btn-default btn-round">
        <i class="ace-icon fa fa-refresh"></i>
        新增
      </button>
    </p>
    <Pagination ref="Pagination" v-bind:list="list"></Pagination>
    <!-- PAGE CONTENT BEGINS -->

    <table id="simple-table" class="table table-bordered table-hover">
      <thead>
        <tr>
          <th>id</th>
          <th>登录名</th>
          <th>昵称</th>
          <th>密码</th>
          <th>操作</th>
        </tr>
      </thead>

      <tbody>
        <tr v-for="user in users" :key="user.id">
          <td>{{ user.id }}</td>
          <td>{{ user.loginName }}</td>
          <td>{{ user.name }}</td>
          <td>{{ user.password }}</td>
          <td>
            <div class="hidden-sm hidden-xs btn-group">
              <button v-on:click="editUser(user)" class="btn btn-xs btn-info">
                <i class="ace-icon fa fa-user bigger-120"></i>
              </button>
              <button v-show="hasResources('010103')"
                v-on:click="editPassword(user)"
                class="btn btn-xs btn-info"
              >
                <i class="ace-icon fa fa-key bigger-120"></i>
              </button>
              <button v-show="hasResources('010101')" v-on:click="edit(user)" class="btn btn-xs btn-info">
                <i class="ace-icon fa fa-pencil bigger-120"></i>
              </button>
              <button  v-show="hasResources('010102')" v-on:click="del(user.id)" class="btn btn-xs btn-danger">
                <i class="ace-icon fa fa-trash-o bigger-120"></i>
              </button>
            </div>
          </td>
        </tr>
      </tbody>
    </table>
    <!-- Modal -->
    <div id="form-modal" class="modal fade" tabindex="-1" role="dialog">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button
              type="button"
              class="close"
              data-dismiss="modal"
              aria-label="Close"
            >
              <span aria-hidden="true">&times;</span>
            </button>
            <h4 class="modal-title">表单</h4>
          </div>
          <div class="modal-body">
            <form class="form-horizontal">
              <div class="form-group">
                <label class="col-sm-2 control-label">登录名</label>
                <div class="col-sm-10">
                  <input
                    v-model="user.loginName"
                    v-bind:disabled="user.id"
                    class="form-control"
                  />
                </div>
              </div>
              <div class="form-group">
                <label class="col-sm-2 control-label">昵称</label>
                <div class="col-sm-10">
                  <input v-model="user.name" class="form-control" />
                </div>
              </div>
              <div v-show="!user.id" class="form-group">
                <label class="col-sm-2 control-label">密码</label>
                <div class="col-sm-10">
                  <input
                    v-model="user.password"
                    type="password"
                    class="form-control"
                  />
                </div>
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button type="button" class="btn btn-default" data-dismiss="modal">
              取消
            </button>
            <button v-on:click="save()" type="button" class="btn btn-primary">
              保存
            </button>
          </div>
        </div>
        <!-- /.modal-content -->
      </div>
      <!-- /.modal-dialog -->
    </div>
    <!-- /.modal -->

    <div
      id="edit-password-modal"
      class="modal fade"
      tabindex="-1"
      role="dialog"
    >
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button
              type="button"
              class="close"
              data-dismiss="modal"
              aria-label="Close"
            >
              <span aria-hidden="true">&times;</span>
            </button>
            <h4 class="modal-title">修改密码</h4>
          </div>
          <div class="modal-body">
            <form class="form-horizontal">
              <div class="form-group">
                <label class="control-label col-sm-2">密码</label>
                <div class="col-sm-10">
                  <input
                    class="form-control"
                    type="password"
                    v-model="user.password"
                    name="password"
                  />
                </div>
              </div>
            </form>
          </div>
          <div class="modal-footer">
            <button
              type="button"
              class="btn btn-white btn-default btn-round"
              data-dismiss="modal"
            >
              <i class="ace-icon fa fa-times"></i>
              取消
            </button>
            <button
              type="button"
              class="btn btn-white btn-info btn-round"
              v-on:click="savePassword()"
            >
              <i class="ace-icon fa fa-plus blue"></i>
              保存密码
            </button>
          </div>
        </div>
        <!-- /.modal-content -->
      </div>
      <!-- /.modal-dialog -->
    </div>
    <!-- /.modal -->

    <!-- 角色用户关联配置 -->
    <div id="user-modal" class="modal fade" tabindex="-1" role="dialog">
      <div class="modal-dialog" role="document">
        <div class="modal-content">
          <div class="modal-header">
            <button
              type="button"
              class="close"
              data-dismiss="modal"
              aria-label="Close"
            >
              <span aria-hidden="true">&times;</span>
            </button>
            <h4 class="modal-title">角色用户关联配置</h4>
          </div>
          <div class="modal-body">
            <div class="row">
              <div class="col-md-6">
                <table id="role-table" class="table table-hover">
                  <tbody>
                    <tr v-for="role in roles" :key="role.id">
                      <td>{{ role.name }}</td>
                      <td class="text-right">
                        <a
                          v-on:click="addRole(role)"
                          href="javascript:;"
                          class=""
                        >
                          <i class="ace-icon fa fa-arrow-circle-right blue"></i>
                        </a>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
              <div class="col-md-6">
                <table id="user-role-table" class="table table-hover">
                  <tbody>
                    <tr v-for="role in userRoles" :key="role.id">
                      <td>{{ role.name }}</td>
                      <td class="text-right">
                        <a
                          v-on:click="deleteRole(role)"
                          href="javascript:;"
                          class=""
                        >
                          <i class="ace-icon fa fa-trash blue"></i>
                        </a>
                      </td>
                    </tr>
                  </tbody>
                </table>
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <button
              type="button"
              class="btn btn-white btn-default btn-round"
              data-dismiss="modal"
            >
              <i class="ace-icon fa fa-times"></i>
              关闭
            </button>
            <button
              type="button"
              class="btn btn-white btn-info btn-round"
              v-on:click="saveUser()"
            >
              <i class="ace-icon fa fa-plus blue"></i>
              保存
            </button>
          </div>
        </div>
        <!-- /.modal-content -->
      </div>
      <!-- /.modal-dialog -->
    </div>
  </div>
  <!-- /.span -->
</template>
<script>
import Pagination from "../../components/pagination";
import Toast from "../../../public/static/js/toast";
import Loading from "../../../public/static/js/loading";
import Confirm from "../../../public/static/js/confirm";
import Validator from "../../../public/static/js/validator";
import Tool from "../../../public/static/js/tool";

export default {
  components: { Pagination },
  name: "users",
  data() {
    return {
      base: `${process.env.VUE_APP_BASE_URL}/system`,
      user: {},
      users: [],
      userRoles: [],
      role: {},
      roles: [],
    };
  },

  mounted: function () {
    // 调用父组件的activeSidebar方法
    // this.$parent.activeSidebar("business-course-sidebar")
    let _this = this;
    // 初始化每页条数
    _this.$refs.Pagination.size = 10;
    _this.list(1);
  },
  methods: {

    hasResources(id) {
      return Tool.hasResources(id)
    },
    addModel() {
      let _this = this;
      _this.user = {};
      $("#form-modal").modal("show");
    },
    list(page) {
      let _this = this;
      Loading.show();
      _this.$axios
        .get(`${_this.base}/admin/users`, {
          params: {
            page: page,
            size: _this.$refs.Pagination.size,
          },
        })
        .then((res) => {
          Loading.hide();
          if (res.data.success) {
            _this.users = res.data.data.list;
            _this.$refs.Pagination.render(page, res.data.data.total);
          }
        });
    },
    save() {
      let _this = this;
      /* if (!Validator.require(_this.user.name, '名称')
                || !Validator.require(_this.user.courseId, '课程ID')
                || !validator.length(_this.user.courseId, '课程ID' , 1, 8)) {
                return
            } */
      Loading.show();
      _this.$axios.post(`${_this.base}/admin/users`, _this.user).then((res) => {
        Loading.hide();
        if (res.data.success) {
          $("#form-modal").modal("hide");
          Toast.success("操作成功");
          _this.list(_this.$refs.Pagination.page);
        } else {
          Toast.warning(res.data.msg);
        }
      });
    },
    edit(user) {
      let _this = this;
      // 使用空对象复制，防止编辑时直接修改data的属性(vue双向绑定会即时渲染)
      _this.user = $.extend({}, user);
      $("#form-modal").modal("show");
    },
    del(userId) {
      Confirm.show("确定要删除吗?", () => {
        let _this = this;
        Loading.show();
        _this.$axios
          .delete(`${_this.base}/admin/users/${userId}`)
          .then((res) => {
            Loading.hide();
            if (res.data.success) {
              Toast.success("删除成功");
              _this.list(_this.$refs.Pagination.page);
            } else {
              Toast.error("删除失败");
            }
          });
      });
    },
    editPassword(user) {
      let _this = this;
      _this.user = $.extend({}, user);
      _this.user.password = null;
      $("#edit-password-modal").modal("show");
    },
    savePassword() {
      let _this = this;
      Loading.show();
      _this.$axios
        .put(`${_this.base}/admin/users`, _this.user)
        .then((response) => {
          Loading.hide();
          let resp = response.data;
          if (resp.success) {
            $("#edit-password-modal").modal("hide");
            _this.list(1);
            Toast.success("保存成功！");
          } else {
            Toast.warning(resp.msg);
          }
        });
    },
    /**
     * 点击【用户】
     */
    editUser(user) {
      let _this = this;
      _this.user = $.extend({}, user);
      _this.listRoles();
      $("#user-modal").modal("show");
    },
    /**
     * 查询全部角色
     */
    listRoles() {
      let _this = this;
      Loading.show();
      _this.$axios
        .get(`${_this.base}/admin/roles`, {
          params: {
            page: 1,
            size: 9999,
          },
        })
        .then((res) => {
          Loading.hide();
          _this.roles = res.data.data.list;
          _this.listUserRole()
        });
    },
    /**
     * 用户中添加角色
     */
    addRole(role) {
      let _this = this;

      // 如果当前要添加的角色在右边列表中已经有了，则不用再添加
      let roles = _this.userRoles;
      for (let i = 0; i < roles.length; i++) {
        if (role === roles[i]) {
          return;
        }
      }
      _this.userRoles.push(role);
    },
    /**
     * 用户中删除角色
     */
    deleteRole(role) {
      let _this = this;
      Tool.removeObj(_this.userRoles, role);
    },

    /**
     * 加载用户的角色
     */
    listUserRole() {
      let _this = this;
      _this.userRoles = [];
      _this.$axios
        .get(`${_this.base}/admin/users/roles/${_this.user.id}`)
        .then((res) => {
          let roleIds = res.data.data;
          // 根据加载到角色ID，到【所有角色数组：roles】中查找角色对象，用于列表显示
          for (let i = 0; i < roleIds.length; i++) {
            for (let j = 0; j < _this.roles.length; j++) {
              if (roleIds[i] === _this.roles[j].id) {
                _this.userRoles.push(_this.roles[j]);
              }
            }
          }
        });
    },
    /**
     * 角色用户模态框点击【保存】
     */
    saveUser() {
      let _this = this;
      let roles = _this.userRoles;

      // 保存时，只需要保存用户id，所以使用id数组进行参数传递
      let roleIds = [];
      for (let i = 0; i < roles.length; i++) {
        roleIds.push(roles[i].id);
      }
      _this.$axios
        .post(`${_this.base}/admin/users/roles`, {
          name: _this.user.name,
          id: _this.user.id,
          roleIds: roleIds,
        })
        .then((res) => {
          if (res.data.success) {
            Toast.success("保存成功!");
          } else {
            Toast.warning(res.data.message);
          }
        });
    },
  },
};
</script>
<style scoped>
img {
  width: 100%;
  height: 20vw;
}
</style>